package com.example.leetcode;

public class StrStr {
    public static void main(String[] args) {
        String haystack = "aa";
        String needle = "aaa";
        System.out.println(strStr(haystack, needle));
    }

    public static int strStr(String haystack, String needle) {
        if (needle == null || haystack == null || needle.length() > haystack.length()) {
            return -1;
        }
        if (needle.length() == 0) {
            return 0;
        }
        char[] haystackChars = haystack.toCharArray();
        char[] needleChars = needle.toCharArray();
        for (int i = 0; i < haystackChars.length; i++) {
            if (haystackChars[i] == needleChars[0]) {
                int tmp = i + 1;
                int j = 1;
                if (tmp > haystackChars.length) {
                    return -1;
                }
                while (j < needleChars.length && tmp < haystackChars.length) {
                    if (needleChars[j]!=haystackChars[tmp]){
                        break;
                    }
                    j++;
                    tmp++;
                }
                if (j==needleChars.length){
                    return i;
                }
            }
        }
        return -1;
    }
}
